package com.macro.mall.review.service.impl;


import com.macro.mall.review.dao.ReviewMapper;
import com.macro.mall.review.dto.ProductReviews;
import com.macro.mall.review.dto.ProductReviewsResponse;
import com.macro.mall.review.dto.ReviewViews;
import com.macro.mall.review.service.ReviewService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 *  评论服务实现类
 */
@Service
@Log4j2
public class ReviewServiceImpl implements ReviewService {
    @Autowired
    private ReviewMapper reviewMapper;

    @Override
    public Page<ProductReviewsResponse> getReviews(Long id, int pageNum, int pageSize) {
        // 开始分页
        PageRequest pageRequest = PageRequest.of(pageNum, pageSize);

        // 查询好评率
        String applauseRate = reviewMapper.getApplauseRate(id);

        // 异步查询评论详情
        CompletableFuture<List<ProductReviews>> listCompletableFuture = CompletableFuture.supplyAsync(() ->
                reviewMapper.getList(id)
        );

        // 获取评论列表
        List<ProductReviews> reviewsList;
        try {
            reviewsList = listCompletableFuture.join();
            log.info("异步评论列表获取成功: {}", reviewsList);
        } catch (Exception e) {
            reviewsList = Collections.emptyList();
            log.error("异步评论列表获取失败: {}", e.getMessage());
            throw new RuntimeException("评论获取失败", e); // 重新抛出异常
        }

        // 创建 ProductReviewsResponse 对象并设置数据
        ProductReviewsResponse productReviewsResponse = new ProductReviewsResponse();
        productReviewsResponse.setApplauseRate(applauseRate);
        productReviewsResponse.setProductReviewsResponses(reviewsList);

        // 返回分页结果
        long total = reviewsList.size(); // 根据实际情况获取总数
        return new PageImpl<>(Collections.singletonList(productReviewsResponse), pageRequest, total);
    }
    @Transactional(rollbackFor = Exception.class)

    @Override
    public Integer add(ReviewViews reviewViews) {
        // 获取商品评论
        ProductReviews productReviews = reviewViews.getProductReviews();

        // 添加商品评论并获取评论 ID
        Integer result = reviewMapper.add(productReviews);

        // 确保评论添加成功后再添加标签
        if (result != null && result > 0) {
            Integer reviewId = productReviews.getId();
            List<Integer> labels = reviewViews.getLabels();

            // 检查 labels 是否不为空，再进行添加
            if (labels != null && !labels.isEmpty()) {
                extracted(labels, reviewId);
            }
        }

        // 使用异步延时模拟耗时操作
        extracted();

        return result;
    }

    private void extracted() {
        final long millis = System.currentTimeMillis();
        try {
            Thread.sleep(1000);
            log.info("加异步注解耗时: {} ms", (System.currentTimeMillis() - millis));
        } catch (InterruptedException e) {
            log.error("延时操作被中断: {}", e.getMessage());
        }
    }

    @Async
    public CompletableFuture<Void> extracted(List<Integer> labels, Integer reviewId) {
        if (labels != null && !labels.isEmpty()) {
            labels.forEach(label -> reviewMapper.addReviews(reviewId, Collections.singletonList(label)));
        }
        return CompletableFuture.completedFuture(null);
    }
}
